import StringUtils from "../../../utils/StringUtils";

const constants = require('../../../common/Constants.js');
const netWork_utils = require('../../../http/NetworkUtils.js');
const regexUtils = require('../../../utils/RegexUtils.js');
const bmap = require('../../../common/bmap-wx.min.js');
import * as util from '../../../utils/UmfUtils';

import * as cacheUtils from '../../../model/CacheUtils';
import PickerUtils from '../../../model/PickerUtils';
import location from '../../../common/code/pickerList/location';
import busTypes from '../../../common/code/pickerList/busTypes';
import { saveAgentCache } from '../../../model/CacheUtils';

import {$Toptips, $Toast} from '../../../components/CompRouter';

var app = getApp();
const StoreInfoPage = {

    /**
     * 初始化店铺信息页
     * @param basisPage
     */
    initStoreInfoPage(basisPage, pageParams) {
        let cacheManager = new cacheUtils.cacheManager();
        cacheManager.init(pageParams["storeId"], constants.STORAGE_FUNC.STORE_INFO);
        let cacheStorageData = cacheManager.getFunc();

        if (!cacheStorageData) {
            //定位
            this.initLocation();
            //没有缓存的场合，取收款人信息填入法人信息
            cacheStorageData = {
                storeMan: pageParams["payeeName"],
                storeManIdentity: pageParams["payeeIdentity"],
                storeManIdentityValid: pageParams["payeeInidcardValid"],
            };
            //没有缓存的场合，收款人信息身份证有效期为长期，法人也为长期
            if (pageParams["payeeInidcardValid"] && pageParams["payeeInidcardValid"]!="2099-09-09"){
              this.setData({
                deadDate:true 
              })
            }
            //同步缓存
            cacheManager.cacheFunc(cacheStorageData);
        }

        //设置实时缓存
        basisPage.setData({
            cacheManager: cacheManager,
            cacheStorageData: cacheStorageData,

            storeCategory: cacheStorageData['storeCategory'],
            storeAddress: cacheStorageData['storeAddress'],
            isEnterprise: cacheStorageData['isEnterprise'],
            registerDate: cacheStorageData['registerDate'],
            storeManIdentityValid: cacheStorageData['storeManIdentityValid'],
            isPos: cacheStorageData["isPos"],
            storeId: pageParams["storeId"]
        });
    },
    /**
     * 是否开通POS
     * @param e
     */
    switchChange: function (e) {
      this.data.cacheManager.cacheFunc({ isPos: e.detail.value==true?'1':'0' })
      this.setData({
        isPos: e.detail.value == true ? '1' : '0'
      })
    },

    /**
     * 店铺全称继承店铺简称
     * @param e
     */
    storeNameFo: function (e) {
        let storeName = e.detail.value;
        if (!storeName) {
            let storeShortName = this.data.cacheManager.getFunc().storeShortName;
            this.setData({
                storeName: storeShortName
            })
        }
    },
    /**
     * 企业或个人单选按钮，选择监听
     * @param e
     */
    radioChange: function (e) {
        this.data.cacheManager.cacheFunc({isEnterprise: e.detail.value === "1"});
        this.setData({
            isEnterprise: e.detail.value === "1"
        })
    },

    /**
     * 显示标签picker
     * @param e
     */
    showLocalNormalPicker: function (e) {
        let index = e.currentTarget.dataset.index;
        if (this.data.__nap && this.data.__nap[index] && this.data.__nap[index].firstList && this.data.__nap[index].firstList.length > 0) {
            this.showNormalPicker(e);
        } else {
            $Toast.showText("暂无历史输入记录,请手动输入标签内容");
        }
    },

    /**
     * 注册日期滚动选择监听
     * @param e
     */
    bindRegisterDateChange: function (e) {
        this.data.cacheManager.cacheFunc({registerDate: e.detail.value==true?1:0})
        this.setData({
            registerDate: e.detail.value
        });
    },
    /**
     * 证件有效期滚动选择监听
     * @param e
     */
    bindCateCardValidChange: function (e) {
        this.data.cacheManager.cacheFunc({storeManIdentityValid: e.detail.value})
        this.setData({
            storeManIdentityValid: e.detail.value
        });
    },

    /**
     * 自定义pickerView选择监听
     * @param idx, ret, code
     */
    onConfirmCB: function (idx, ret, code) {
        if (idx === 0) {
            this.data.cacheManager.cacheFunc({storeCategory: ret.join('/')});
            this.setData({
                storeCategory: ret.join('/')
            });
        } else if (idx === 1) {
            this.data.cacheManager.cacheFunc({storeAddress: ret.join('/')})
            this.setData({
                storeAddress: ret.join('/')
            });
        }

    },

    /**
     * 提交店铺信息
     */
    storeInfoSubmit: function (e) {
        let formValues = e.detail.value;
        formValues.formId = e.detail.formId;
        if (!this.data.storeManIdentityValid) {
          this.setData({
            storeManIdentityValid:"2099-09-09"
          })
        }
        formValues.storeManIdentity = util.removeSpace(formValues.storeManIdentity);

        let errorMsg = this._p_checkForm(formValues);
        if (errorMsg) {
            $Toptips.error({text: errorMsg});
        } else {
            //缓存最新使用的邮箱及标签
            this._saveStoreEmail(formValues.storeEmail);
            this._saveAnnotations(formValues.labelOne, formValues.labelTwo);

            this._postStoreInfo(formValues);
        }
    },

    /**
     * 表单验证
     * @param formValues
     * @returns {*}
     * @private
     */
    _p_checkForm(formValues) {
        let baseValues = [
            [formValues.storeShortName, constants.RegexTypes.MERCHANT_NAME],//商户简称
            [formValues.storeFullAddress, constants.RegexTypes.DETAIL_ADD],//详细地址
            [formValues.fixline, constants.RegexTypes.FIXLINE],//客服电话
        ];

        //[立马付运营优化二期] 商户邮箱有的场合校验
        formValues.storeEmail && baseValues.push([formValues.storeEmail, constants.RegexTypes.LINKTELEMAIL]);

        let errorMsg = regexUtils.regexTypesWithMsg(baseValues);
        if (errorMsg) {
            return errorMsg;
        }
        if (!this.data.storeCategory) {
            return "请选择正确的商户类别";
        }
        if (!this.data.storeAddress) {
            return "请选择正确的商户地址";
        }
	    if (StringUtils.safeTrim(formValues.labelTwo).length > 0 && StringUtils.safeTrim(formValues.labelOne).length <= 0) {
            return "请输标签一内容";
        }
        if (this.data.isEnterprise) {
            let storeValues = [
                [formValues.licenseNo, constants.RegexTypes.BUSILICENSENO],//营业执照
                [formValues.storeName, constants.RegexTypes.MERCHANTFULLNAME],//商户全称
                [formValues.storeKind, constants.RegexTypes.MAINBUSINESS],//经营类别
                [formValues.registerAddress, constants.RegexTypes.REGISTEREDADDR],//注册地址
                [formValues.storeMan, constants.RegexTypes.PROPRIETORNAME],//法人
                [formValues.storeManIdentity, constants.RegexTypes.ID_CARD],//法人身份证
            ];
            errorMsg = regexUtils.regexTypesWithMsg(storeValues);
            if (errorMsg) {
                return errorMsg;
            }
            if (!this.data.registerDate) {
                return "请选择注册日期";
            }
            if (!this.data.storeManIdentityValid) {
                return "请选择证件有效期";
            }
        }
        return '';
    },
    /**
     * 定位
     */
    initLocation() {
        let BMap = new bmap.BMapWX({
            ak: constants.LOCATION_AK
        });
        let fail = function (data) {
        };
        let success = (data) => {
            //把所有数据放在初始化data内
            let ret = [
                data.originalData.result.addressComponent.province,
                data.originalData.result.addressComponent.city,
                data.originalData.result.addressComponent.district
            ];

            this.setData({
                [`__ap[${1}].value`]: ret.join('/'),
                wxMarkerData: data.wxMarkerData,
                storeAddress: ret.join('/'),
            });
            this.data.cacheManager.cacheFunc({storeAddress: ret.join('/')})
        };
        // 发起regeocoding检索请求
        BMap.regeocoding({
            fail: fail,
            success: success
        });
    },

    //网络请求
    _postStoreInfo(formValues) {
      if(!this.data.deadDate){
        formValues.storeManIdentityValid = this.data.storeManIdentityValid
      }
        let params = {
            formId: formValues.formId,

            storeId: this.data.storeId,
            storeShortName: formValues.storeShortName,
            storeCategory: PickerUtils.getLinkedCodeByHZ(busTypes, this.data.storeCategory).join(","),
            storeAddress: PickerUtils.getLinkedCodeByHZ(location, this.data.storeAddress).join(","),
            storeFullAddress: formValues.storeFullAddress,
            email: formValues.storeEmail,
            phone: formValues.fixline,
            storeType: formValues.storeType,
            licenseNo: formValues.licenseNo,
            storeName: formValues.storeName,
            registerDate: this.data.registerDate ? this.data.registerDate : this.data.cacheStorageData.registerDate,
            storeKind: formValues.storeKind,
            registerAddress: formValues.registerAddress,
            storeMan: formValues.storeMan,
            storeManIdentity: formValues.storeManIdentity,
            storeManIdentityValid: formValues.storeManIdentityValid ? formValues.storeManIdentityValid : this.data.cacheStorageData.storeManIdentityValid,
            longitude: this.data.wxMarkerData ? this.data.wxMarkerData[0].longitude + '' : '',
            latitude: this.data.wxMarkerData ? this.data.wxMarkerData[0].latitude + '' : '',
            mobileLocation: this.data.wxMarkerData ? this.data.wxMarkerData[0].address : '',
            //[结算账单优化工单]
            labelOne: formValues.labelOne,
            labelTwo: formValues.labelTwo,
            isPos: formValues.isPos==true?"1":"0",
        };
        netWork_utils.buildRequest(constants.Interfaces.FUNC_UPDATE_STOREINF, params, {
            doHttpSucess: (response) => {
                if (constants.RetCodes.SUCCESS === response.retCode) {

                    this.data.cacheManager.clearFunc();
                    this.stepTo(2, response);
                    return true;
                }
                return false;
            }
        }).send();
    },

    /**
     * [立马付运营优化二期] 代理商账号维度保存商户邮箱
     * @param storeEmail
     * @private
     */
    _saveStoreEmail(storeEmail) {
        if (storeEmail) {
            let agentCache = app.globalData.agentCache;
            agentCache.storeEmail = this._getAnnoList(storeEmail, agentCache.storeEmail);
            saveAgentCache(agentCache);
        }
    },

    /**
     * [结算账单优化工单] 保存最近使用的标签
     * @param labelOne
     * @param labelTwo
     * @private
     */
    _saveAnnotations(labelOne, labelTwo) {
        let labelList1 = util.getStorageSync(constants.Keys.ANNO_LIST_1);
        let labelList2 = util.getStorageSync(constants.Keys.ANNO_LIST_2);
        labelList1 = this._getAnnoList(labelOne, labelList1);
        labelList2 = this._getAnnoList(labelTwo, labelList2);

        StringUtils.safeTrim(labelOne) && util.setStorageSync(constants.Keys.ANNO_LIST_1, labelList1);
        StringUtils.safeTrim(labelTwo) && util.setStorageSync(constants.Keys.ANNO_LIST_2, labelList2);
    },

    _getAnnoList(label, labelList) {
        if (label) {
            labelList = labelList ? labelList : [];
            let index = labelList.indexOf(label);
            if (index < 0) {
                //记录中没有
                labelList.unshift(label);
                if (labelList.length > 10) {
                    //最近10条
                    labelList = labelList.slice(0, 10);
                }
            } else {
                //记录中有
                labelList.splice(index, 1);
                labelList.unshift(label);
            }
        }
        return labelList;
    }
};

export default StoreInfoPage;